<template>
  <div style="  padding: 20px;  background-color: #f5f5f5;  min-height: 80vh;">
    <!-- 页面标题 -->
    <h2>溯源管理</h2>

    <!-- 操作按钮区域 -->
    <div
      style="display: flex;  justify-content: space-between;  align-items: center;  margin-bottom: 20px;padding: 16px 20px;background: white;  border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" :disabled="!hasSelectedItems" @click="handleBatchDelete">批量删除</el-button>
      <div class="action-right">
        <el-button @click="list()">刷新</el-button>
        <el-button @click="refreshCompleteness" type="success">刷新完整度</el-button>
        <el-button @click="toggleMoreQuery">更多查询</el-button>
      </div>
    </div>

    <!-- 更多查询区域 -->
    <div v-if="showMoreQuery"
      style="margin-bottom: 20px;padding: 20px;background: white;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
      <el-form :model="page" inline>
        <el-form-item label="商品名称">
          <el-input v-model="page.ShopName" placeholder="输入进行查询" clearable />
        </el-form-item>
        <el-form-item label="生产批次">
          <el-input v-model="page.Production" placeholder="输入进行查询" clearable />
        </el-form-item>
        <el-form-item label="保质期(天)">
          <el-input v-model="page.Expiration" placeholder="输入进行查询" clearable />
        </el-form-item>
        <el-form-item label="生产许可证号">
          <el-input v-model="page.ExpNumber" placeholder="输入进行查询" clearable />
        </el-form-item>
        <el-form-item label="生产企业">
          <el-input v-model="page.Enterprise" placeholder="输入进行查询" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="list">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" @selection-change="SelectionChange" border stripe class="traceability-table">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="shopName" label="商品名称" min-width="120" />
      <el-table-column prop="production" label="生产批次" min-width="150" />
      <el-table-column prop="expiration" label="保质期(天)" min-width="110" />
      <el-table-column prop="expNumber" label="生产许可证号" min-width="160" />
      <el-table-column prop="enterprise" label="生产企业" min-width="200" />
      <el-table-column prop="completeness" label="信息完善度" min-width="120">
        <template #header>
          <div class="column-header">
            <span>信息完善度</span>
            <el-tooltip content="计算公式：(基本信息模块填写数 + 养殖信息模块填写数+ 屠宰信息模块填写数 + 深加工信息模块填写数) / 总模块数 × 100%，保留2位小数"
              placement="top">
              <el-icon class="info-icon">
                <InfoFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
        <template #default="{ row }">
          <span :class="getCompletenessClass(row.completeness)">
            {{ row.completeness }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewDetails(row)">
            详情
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            修改
          </el-button>
          <el-button type="primary" link @click="handleExportCode(row)">
            导出溯源码
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <el-pagination v-model:current-page="page.Pageindex" v-model:page-size="page.Pagesize"
      :page-sizes="[100, 200, 300, 400]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount"
      @size-change="list()" @current-change="list()" prev-text="上一页" next-text="下一页" />

    <!-- 新增弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :before-close="handleDialogClose">
      <el-form :model="form">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-select v-model="form.shopName" placeholder="--请选择--">
            <el-option label="兔腿(大)" value="兔腿(大)" />
            <el-option label="兔肉丁" value="兔肉丁" />
            <el-option label="兔腿(小)" value="兔腿(小)" />
            <el-option label="麻辣兔头" value="麻辣兔头" />
            <el-option label="凉拌兔耳朵" value="凉拌兔耳朵" />
          </el-select>
        </el-form-item>
        <el-form-item label="保质期(天)" :label-width="formLabelWidth">
          <el-input v-model="form.expiration" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产企业" :label-width="formLabelWidth">
          <el-input v-model="form.enterprise" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="form.shopPic"
            :preview-src-list="[form.shopPic]" fit="cover" />
          <el-upload class="upload-demo" :http-request="uploadShopPic" :on-success="handleShopPicSuccess"
            :before-upload="beforeUpload" :limit="1" :file-list="shopPicFileList" list-type="picture" name="file">
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <template #tip>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品质检图" :label-width="formLabelWidth">
          <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="form.pic"
            :preview-src-list="[form.pic]" fit="cover" />
          <el-upload class="upload-demo" :http-request="uploadPic" :on-success="handlePicSuccess"
            :before-upload="beforeUpload" :limit="1" :file-list="picFileList" list-type="picture" name="file">
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <template #tip>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSource">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改弹窗 -->
    <el-dialog v-model="dialogVisibleupdate" :title="dialogTitle" width="80%">
      <el-form :model="formupdate">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-select v-model="formupdate.shopName" placeholder="--请选择--">
            <el-option label="兔腿(大)" value="兔腿(大)" />
            <el-option label="兔肉丁" value="兔肉丁" />
            <el-option label="兔腿(小)" value="兔腿(小)" />
            <el-option label="麻辣兔头" value="麻辣兔头" />
            <el-option label="凉拌兔耳朵" value="凉拌兔耳朵" />
          </el-select>
        </el-form-item>
        <el-form-item label="保质期(天)" :label-width="formLabelWidth">
          <el-input v-model="formupdate.expiration" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产企业" :label-width="formLabelWidth">
          <el-input v-model="formupdate.enterprise" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="formupdate.shopPic"
            :preview-src-list="[formupdate.shopPic]" fit="cover" />
          <el-upload class="upload-demo" :http-request="uploadShopPic" :on-success="handleShopPicSuccess"
            :before-upload="beforeUpload" :limit="1" :file-list="shopPicFileList" list-type="picture" name="file">
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <template #tip>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品质检图" :label-width="formLabelWidth">
          <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="formupdate.pic"
            :preview-src-list="[formupdate.pic]" fit="cover" />
          <el-upload class="upload-demo" :http-request="uploadPic" :on-success="handlePicSuccess"
            :before-upload="beforeUpload" :limit="1" :file-list="picFileList" list-type="picture" name="file">
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <template #tip>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="UpdateSource">修改</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出溯源码弹窗 -->
    <el-dialog v-model="exportDialogVisible" title="导出溯源码" width="400px">
      <div class="export-settings">
        <el-form :model="exportForm" label-width="120px">
          <el-form-item label="导出格式">
            <el-radio-group v-model="exportForm.format">
              <el-radio label="qr">二维码</el-radio>
              <el-radio label="barcode">条形码</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExportConfirm" :loading="exportLoading">
            {{ exportLoading ? '生成中...' : '确定导出' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import myAxios from '@/http/MyAxios'
import QRCode from 'qrcode'
import JsBarcode from 'jsbarcode'
import html2canvas from 'html2canvas'

// 响应式数据
const tableData = ref<any[]>([])

// 信息完整度计算函数
const calculateCompleteness = async (sourceId: string) => {
  try {
    //基本信息
    const basicInfoCount = await getBasicInfoCount(sourceId)
    //养殖
    const breedingInfoCount = await getBreedingInfoCount(sourceId)
    //屠宰
    const slaughterInfoCount = await getSlaughterInfoCount(sourceId)
    //深加工
    const processInfoCount = await getProcessInfoCount(sourceId)
    //总数
    const totalFilled = basicInfoCount + breedingInfoCount + slaughterInfoCount + processInfoCount
    const totalModules = 19
    const completeness = ((totalFilled / totalModules) * 100).toFixed(2)

    return `${completeness}%`
  } catch (error) {
    console.error('计算信息完整度时出错:', error)
    return '0.00%'
  }
}

// 获取基本信息模块填写数
const getBasicInfoCount = async (sourceId: string) => {
  try {
    const response = await myAxios.get("api/Source/GetSourceById", { params: { id: sourceId } })
    if (response.data.code === 10200 && response.data.data) {
      const data = response.data.data
      let count = 0

      // 基本信息模块有7个字段需要检查
      if (data.shopName && data.shopName.trim() !== '') count++
      if (data.production && data.production.trim() !== '') count++
      if (data.expiration && data.expiration.toString().trim() !== '') count++
      if (data.expNumber && data.expNumber.trim() !== '') count++
      if (data.enterprise && data.enterprise.trim() !== '') count++
      if (data.shopPic && data.shopPic.trim() !== '') count++
      if (data.pic && data.pic.trim() !== '') count++

      return count
    }
    return 0
  } catch (error) {
    console.error('获取基本信息失败:', error)
    return 0
  }
}

// 获取养殖信息模块填写数
const getBreedingInfoCount = async (sourceId: string) => {
  try {
    const response = await myAxios.get("/api/Feed/ListFeed", { params: { SourceId: sourceId } })
    if (response.data.code === 10200 && response.data.data && response.data.data.length > 0) {
      const data = response.data.data[0]
      let count = 0

      // 养殖信息模块有9个字段需要检查
      if (data.feedVariety && data.feedVariety.trim() !== '') count++
      if (data.feedSource && data.feedSource.trim() !== '') count++
      if (data.feedDays && data.feedDays.toString().trim() !== '') count++
      if (data.feedFoodName && data.feedFoodName.trim() !== '') count++
      if (data.feedName && data.feedName.trim() !== '') count++
      if (data.leaveDate && data.leaveDate.trim() !== '') count++
      if (data.companiesName && data.companiesName.trim() !== '') count++
      if (data.pic && data.pic.trim() !== '') count++
      if (data.companiesPic && data.companiesPic.trim() !== '') count++

      return count
    }
    return 0
  } catch (error) {
    console.error('获取养殖信息失败:', error)
    return 0
  }
}

// 获取屠宰信息模块填写数
const getSlaughterInfoCount = async (sourceId: string) => {
  try {
    const response = await myAxios.get("/api/Kill/ListKill", { params: { Id: sourceId } })
    if (response.data.code === 10200 && response.data.data && response.data.data.length > 0) {
      const data = response.data.data[0]
      let count = 0

      // 屠宰信息模块有5个字段需要检查
      if (data.height && data.height.toString().trim() !== '') count++
      if (data.beginTime && data.beginTime.trim() !== '') count++
      if (data.endTime && data.endTime.trim() !== '') count++
      if (data.killPic && data.killPic.trim() !== '') count++
      if (data.businessName && data.businessName.trim() !== '') count++

      return count
    }
    return 0
  } catch (error) {
    console.error('获取屠宰信息失败:', error)
    return 0
  }
}

// 获取深加工信息模块填写数
const getProcessInfoCount = async (sourceId: string) => {
  try {
    const response = await myAxios.get("/api/Process/ListProcess", { params: { SourceId: sourceId } })
    if (response.data.code === 10200 && response.data.data && response.data.data.length > 0) {
      const data = response.data.data[0]
      let count = 0

      // 深加工信息模块有5个字段需要检查
      if (data.team && data.team.trim() !== '') count++
      if (data.chargeName && data.chargeName.trim() !== '') count++
      if (data.foodSafetyId && data.foodSafetyId.toString().trim() !== '') count++
      if (data.pic && data.pic.trim() !== '') count++
      if (data.corporateName && data.corporateName.trim() !== '') count++

      return count
    }
    return 0
  } catch (error) {
    console.error('获取深加工信息失败:', error)
    return 0
  }
}

//查询信息
const page = ref({
  Pageindex: 1,
  Pagesize: 50,
  totalpage: 0,
  totalcount: 0,
  ShopName: "",
  Production: "",
  Expiration: 0,
  ExpNumber: "",
  Enterprise: ""
})
const router = useRouter()

//显示
const list = async () => {
  const res = await myAxios.get("api/Source/ListSource", { params: page.value })
  tableData.value = res.data.data
  console.log(tableData.value);
  // 为每个溯源产品计算信息完整度
  for (const item of tableData.value) {
    item.completeness = await calculateCompleteness(item.id)
  }

  page.value.totalcount = res.data.totalcount
  page.value.totalpage = res.data.totalpage

}

//修改    
const handleEdit = (row: any) => {
  dialogTitle.value = '修改溯源管理'
  Object.assign(formupdate.value, row);
  dialogVisibleupdate.value = true
}
const UpdateSource = async () => {
  try {
    const res = await myAxios.post("/api/Source/UpdateSource", formupdate.value)
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message)
      await list() // 重新加载数据并计算信息完整度
    }
    else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    console.error('更新溯源信息失败:', error)
    ElMessage.error('更新失败')
  }
}

//添加溯源基础信息的所需参数
const form = ref({
  "enterprise": "",
  "shopName": "",
  "expiration": 0,
  "pic": "",
  "shopPic": "",
  "accountName": window.sessionStorage.getItem("accountName")
})

//修改溯源基础信息的所需参数
const formupdate: any = ref({
  "id": 0,
  "enterprise": "",
  "shopName": "",
  "expiration": 0,
  "pic": "",
  "shopPic": "",
  "accountName": window.sessionStorage.getItem("accountName")
})

// 图片上传相关数据
const shopPicFileList = ref([])
const picFileList = ref([])

//添加
const addSource = async () => {
  try {
    const res = await myAxios.post("/api/Source/AddSource", form.value)
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message)
      await list() // 重新加载数据并计算信息完整度
    }
    else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    console.error('添加溯源信息失败:', error)
    ElMessage.error('添加失败')
  }
}
///溯源信息删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除溯源产品"${row.shopName}"？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await myAxios.post("/api/Source/DeleteSource", { id: row.id })
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      await list() // 重新加载数据并计算信息完整度
    }
    else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除溯源信息失败:', error)
      ElMessage.error('删除失败')
    }
  }
}
// 图片上传  商品图片
const handleShopPicSuccess = (res: any) => {
  // 请求中的data
  if (res && res.data) {
    form.value.shopPic = res.data
    ElMessage.success('封面图上传成功')
  } else {
    ElMessage.error('封面图上传失败')
  }
}
//图片上传  质检图片
const handlePicSuccess = (res: any) => {
  if (res && res.data) {
    form.value.pic = res.data
    ElMessage.success('产品质检图上传成功')
  } else {
    ElMessage.error('产品质检图上传失败')
  }
}
//图片上传限制信息
const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt500K = file.size / 1024 < 500

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt500K) {
    ElMessage.error('上传图片大小不能超过 500KB!')
  }
  return isJPG && isLt500K
}

//  封面图
const uploadShopPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

// 自定义上传函数 - 产品质检图
const uploadPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

const selectedItems = ref<any[]>([])
const showMoreQuery = ref(false)
const dialogVisible = ref(false)
const dialogVisibleupdate = ref(false)
const exportDialogVisible = ref(false)
const dialogTitle = ref('新增溯源管理')
const formLabelWidth = '140px'
const exportForm = reactive({
  format: 'qr',
  quantity: 1
})

// 当前选中的溯源产品
const currentExportRow = ref<any>(null)

// 导出加载状态
const exportLoading = ref(false)

// 计算属性
const hasSelectedItems = computed(() => selectedItems.value.length > 0)

// 计算信息完整度的样式类
const getCompletenessClass = (completeness: string) => {
  return {
    'completeness-100': completeness === '100.00%',
    'completeness-low': completeness !== '100.00%'
  }
}


//新增溯源管理弹窗
const handleAdd = () => {
  dialogTitle.value = '新增溯源管理'
  dialogVisible.value = true
}

//批量删除操作
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }
  ElMessageBox.confirm(
    `确认删除已选的${selectedItems.value.length}个溯源产品？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  const ids = selectedItems.value.map(item => item.id)
  myAxios.post('/api/Source/BatchDeleteSource', { ids }).then(res => {
    if (res.data.code === 10200) {
      ElMessage.success(res.data.message || '删除成功')
      // 清空选中项
      selectedItems.value = []
      // 刷新数据
      list()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  })
}

//更多查询显示
const toggleMoreQuery = () => {
  showMoreQuery.value = !showMoreQuery.value
}

// 刷新信息完整度
const refreshCompleteness = async () => {
  try {
    ElMessage.info('正在重新计算信息完整度...')
    await list() // 重新加载数据并计算信息完整度
    ElMessage.success('信息完整度计算完成')
  } catch (error) {
    console.error('刷新信息完整度失败:', error)
    ElMessage.error('刷新失败')
  }
}

//重置查询条件
const handleReset = () => {
  page.value.Enterprise = ""
  page.value.ExpNumber = ""
  page.value.Expiration = 0
  page.value.Production = ""
  page.value.ShopName = ""
  ElMessage.primary('查询条件已重置')
  list()
}

// 批量删除  选中
const SelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

//跳转页面
const handleViewDetails = (row: any) => {
  router.push({
    path: '/slaughter', query: {
      SourceId: row.id,
      shopName: row.shopName,
      production: row.production,
      expiration: row.expiration,
      expNumber: row.expNumber,
      enterprise: row.enterprise,
      shopPic: row.shopPic,
      pic: row.pic
    }
  })
}
//导出溯源码
const handleExportCode = (row: any) => {
  currentExportRow.value = row
  exportDialogVisible.value = true
}
const handleDialogClose = () => {
  dialogVisible.value = false
}

//导出溯源码
const handleExportConfirm = async () => {
  if (!currentExportRow.value) {
    ElMessage.error('未选择要导出的溯源产品')
    return
  }

  try {
    exportLoading.value = true
    ElMessage.info('正在生成溯源码...')

    // 生成溯源码内容
    const traceCode = generateTraceCode(currentExportRow.value)

    if (exportForm.format === 'qr') {
      await exportQRCode(traceCode, currentExportRow.value.shopName)
    } else {
      await exportBarcode(traceCode, currentExportRow.value.shopName)
    }

    ElMessage.success('溯源码导出成功')
    exportDialogVisible.value = false
  } catch (error) {
    console.error('导出溯源码失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 生成溯源码内容
const generateTraceCode = (row: any) => {
  if (!row || !row.id) {
    return '请选择溯源产品'
  }
  const baseUrl = window.location.origin
  const traceUrl = `${baseUrl}/trace-detail?id=${row.id}&shopName=${encodeURIComponent(row.shopName || '')}&production=${encodeURIComponent(row.production || '')}`
  return traceUrl
}

// 导出二维码
const exportQRCode = async (content: string, productName: string) => {
  try {
    // 创建二维码
    const qrDataUrl = await QRCode.toDataURL(content, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })

    // 包含二维码的HTML内容
    const htmlContent = `
      <div style="padding: 30px; text-align: center; font-family: Arial, sans-serif; background: #ffffff;">
        <h1 style="margin: 0 0 25px 0; color: #303133; font-size: 24px; font-weight: bold;">${productName} - 产品溯源码</h1>
        
        <div style="margin: 25px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e4e7ed;">
          <img src="${qrDataUrl}" style="max-width: 280px; border: 1px solid #ddd; padding: 15px; background: white; border-radius: 6px;" />
        </div>
        
        <div style="margin: 20px 0; text-align: left; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #409eff;">
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>商品名称：</strong>${currentExportRow.value.shopName}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>生产批次：</strong>${currentExportRow.value.production}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>生产企业：</strong>${currentExportRow.value.enterprise}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>保质期：</strong>${currentExportRow.value.expiration}天</p>
        </div>
        
        <p style="margin: 15px 0; color: #409eff; font-size: 16px; font-weight: 600;">扫描二维码查看完整产品溯源信息</p>
        <p style="margin: 10px 0; color: #909399; font-size: 12px;">生成时间: ${new Date().toLocaleString('zh-CN')}</p>
        <p style="margin: 5px 0; color: #c0c4cc; font-size: 11px;">爱吃兔溯源管理系统</p>
      </div>
    `

    // 创建临时容器
    const container = document.createElement('div')
    container.innerHTML = htmlContent
    container.style.position = 'absolute'
    container.style.left = '-9999px'
    container.style.top = '-9999px'
    document.body.appendChild(container)

    // 转换为图片
    const canvas = await html2canvas(container, {
      backgroundColor: '#ffffff',
      scale: 2,
      useCORS: true
    })

    // 下载图片
    const link = document.createElement('a')
    link.download = `${productName}_溯源码_${new Date().getTime()}.png`
    link.href = canvas.toDataURL()
    link.click()

    // 清理临时元素
    document.body.removeChild(container)
  } catch (error) {
    console.error('生成二维码失败:', error)
    throw error
  }
}

// 导出条形码
const exportBarcode = async (content: string, productName: string) => {
  try {
    // 创建临时canvas元素
    const canvas = document.createElement('canvas')
    canvas.width = 400
    canvas.height = 200

    // 生成条形码
    JsBarcode(canvas, content, {
      format: "CODE128",
      width: 2,
      height: 100,
      displayValue: true,
      fontSize: 16,
      margin: 10
    })

    // 创建包含条形码的HTML内容
    const barcodeDataUrl = canvas.toDataURL()
    const htmlContent = `
      <div style="padding: 30px; text-align: center; font-family: Arial, sans-serif; background: #ffffff;">
        <h1 style="margin: 0 0 25px 0; color: #303133; font-size: 24px; font-weight: bold;">${productName} - 产品溯源码</h1>
        
        <div style="margin: 25px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e4e7ed;">
          <img src="${barcodeDataUrl}" style="max-width: 380px; border: 1px solid #ddd; padding: 15px; background: white; border-radius: 6px;" />
        </div>
        
        <div style="margin: 20px 0; text-align: left; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #409eff;">
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>商品名称：</strong>${currentExportRow.value.shopName}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>生产批次：</strong>${currentExportRow.value.production}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>生产企业：</strong>${currentExportRow.value.enterprise}</p>
          <p style="margin: 8px 0; color: #606266; font-size: 14px;"><strong>保质期：</strong>${currentExportRow.value.expiration}天</p>
        </div>
        
        <p style="margin: 15px 0; color: #409eff; font-size: 16px; font-weight: 600;">扫描条形码查看完整产品溯源信息</p>
        <p style="margin: 10px 0; color: #909399; font-size: 12px;">生成时间: ${new Date().toLocaleString('zh-CN')}</p>
        <p style="margin: 5px 0; color: #c0c4cc; font-size: 11px;">爱吃兔溯源管理系统</p>
      </div>
    `

    // 创建临时容器
    const container = document.createElement('div')
    container.innerHTML = htmlContent
    container.style.position = 'absolute'
    container.style.left = '-9999px'
    container.style.top = '-9999px'
    document.body.appendChild(container)

    // 转换为图片
    const finalCanvas = await html2canvas(container, {
      backgroundColor: '#ffffff',
      scale: 2,
      useCORS: true
    })

    // 下载图片
    const link = document.createElement('a')
    link.download = `${productName}_溯源码_${new Date().getTime()}.png`
    link.href = finalCanvas.toDataURL()
    link.click()

    // 清理临时元素
    document.body.removeChild(container)
  } catch (error) {
    console.error('生成条形码失败:', error)
    throw error
  }
}

onMounted(() => {
  list()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  font-size: 18px;
}

.action-right {
  display: flex;
  gap: 12px;
}

.traceability-table {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.column-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.column-header .el-input {
  width: 100%;
}

.info-icon {
  color: #409eff;
  cursor: pointer;
  margin-left: 4px;
}

.completeness-100 {
  color: #67c23a;
  font-weight: 600;
}

.completeness-low {
  color: #f56c6c;
  font-weight: 600;
}

.upload-demo {
  width: 100%;
}

.upload-demo :deep(.el-upload-list__item) {
  width: 200px;
}

.upload-demo :deep(.el-upload--picture) {
  max-width: 300px;
}

.upload-icon {
  width: 50px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-icon:hover {
  border-color: #409eff;
}

.upload-icon svg {
  width: 20px;
  height: 20px;
  color: #8c939d;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-content {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.export-settings {
  padding: 20px 0;
}



.completeness-info {
  line-height: 1.8;
}

.completeness-info ul {
  margin: 10px 0;
  padding-left: 20px;
}

.completeness-info li {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .traceability-container {
    padding: 10px;
  }

  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .action-right {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 16px;
  }
}
</style>
